/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld.sensortasks;

import com.sun.squawk.util.IntHashtable;

/**
 * A SensorTask that shares its slot among a list of SensorTasks
 * @author me
 */
public final class SharedSensorTask extends SensorTask {
    private IntHashtable tasks;
    private int index = 0;
    private int repeatEvery;
    
    /**
     * Creates a new instance of SharedSensorTask
     * @param interval - the slot size of this SharedSensorTask
     * @param repeatEveryXFrames - The number of turns among which to share the time slot
     */
    public SharedSensorTask(long interval, int repeatEveryXFrames) {
        super.sampleInterval = interval;
        repeatEvery = repeatEveryXFrames;
    }
    
    protected SensorTask copy() {
        SharedSensorTask task = new SharedSensorTask(super.sampleInterval, repeatEvery);
        task.setRepeat(repeating);
        task.tasks = this.tasks;
        return task;
    }
    
    /**
     * schedule a sensor task to use the SharedSensorTask's timeslot during turn frameSlot
     * @param task
     * @param frameSlot - the turn to assign to this SensorTask.  Should be between 0 and repeatEveryXTimes
     */
    public void addSensorTask(SensorTask task, int frameSlot) {
        tasks.put(frameSlot, task);
    }
    
    /**
     * Runs the SensorTask whose turn it is, or does nothing if no SensorTask is registered for this frame repeat
     */
    public void runTask() {
        if (tasks.containsKey(index)) {
            ((SensorTask)tasks.get(index)).runTask();
        }
        index = (index+1)%repeatEvery;
    }
}
